package com.lengxf.netty.config;

import cn.hutool.core.lang.Assert;
import com.lengxf.netty.config.initializer.WebSocketClientInitializer;
import com.lengxf.netty.config.listener.ConnectionListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;

/**
 * @author Lengxf
 * @version 1.0.0
 * @ClassName Test1.java
 * @Description
 * @createTime 2022-10-10日 17:40:00
 */
@Slf4j
public class NettyClient {

    private final static URI uri = NettyClientConfig.getServerUri();
    private final EventLoopGroup loop = new NioEventLoopGroup();

    public void createBootstrap(Bootstrap bootstrap, EventLoopGroup eventLoop) {
        Assert.notNull(bootstrap);
        ChannelContextHolder.setShouldReconnect(false);
        bootstrap.group(eventLoop)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new WebSocketClientInitializer())
                .remoteAddress(uri.getHost(), uri.getPort())
                .connect()
                .addListener(new ConnectionListener());
    }


    public void run() {
        createBootstrap(new Bootstrap(), loop);
    }
}
